package org.apache.ibatis.common.reflection.invoker;

import org.apache.ibatis.common.reflection.Reflector;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @Name GetFieldInvoker
 * @Description: {获取目标属性值} 执行器 [实现] 类
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-04-25 15:05:29
 **/
public class GetFieldInvoker implements Invoker {
    // 目标属性
    private final Field field;

    public GetFieldInvoker(Field field) {
        this.field = field;
    }

    @Override
    public Class<?> getType() {
        return field.getType();
    }

    @Override
    public Object invoke(Object target, Object[] args) throws IllegalAccessException, InvocationTargetException {
        try {
            // 1. 直接通过反射获取目标属性的值
            return field.get(target);
        } catch (IllegalAccessException e) {
            // 如果发生异常，则修改目标属性的访问权限后再次尝试获取属性值
            if (Reflector.canControlMemberAccessible()) {
                field.setAccessible(true);
                return field.get(target);
            } else {
                throw e;
            }
        }
    }
}

